#include <stdio.h>
#include <string.h>

#include "multipart_parser.h"

int file_count = 0;

int part_begin_cb(multipart_parser_t *parser) {
    fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__,__FUNCTION__);

    snprintf(parser->path, sizeof(parser->path), "upload%d.out", file_count);

    return 0;
}

int part_data_cb(multipart_parser_t *parser, const char *at, int length) {
    FILE *fp;
    fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__,__FUNCTION__);

    fp = fopen(parser->path, "ab");
    if(fp) {
        fwrite(at, length, 1, fp);
        fclose(fp);
    }

    return 0;
}

int part_end_cb(multipart_parser_t *parser) {
    file_count++;

    return 0;
}

int main() {
    multipart_parser_t *parser = multipart_parser_new(part_begin_cb, part_data_cb, part_end_cb);

    char buf[4096];

    FILE *fp = fopen("upload.in", "rb");
    int nread;

    if(fp) {
        while((nread = fread(buf, 1, sizeof(buf), fp)) > 0) {
            if(multipart_parser_execute(parser, buf, nread) < 0) {
                fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__,__FUNCTION__);
                break;
            }
        }

        fclose(fp);
    }

    multipart_parser_free(parser);

    getchar();
    return 0;
}

